import Vue from 'vue'
import Vuex from 'vuex'
import api from 'api'
import sha1 from 'js-sha1'
import Cookies from 'js-cookie'
import tactical from './tactical'
import sale from './sale'
import smartCourse from './smartCourse'
import score from './score'
import program from './program'
import grade from './grade'

Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'

// 页面切换loader对象
let loader = {
  fetchCount: 0, // 接口请求数
  timer: null, // 路由延时器
  onComplete: null // 接口请求完成后调用
}

// state
let state = {
  loading: false,
  orgUserId: Cookies.get('orgUserId'),
  global: { // 公共数据
    user: {}
  },
  roleInfo: {}
}

// getters
const getters = {
  global: state => state.global
}

// actions
const actions = {
  getUserInfo ({commit, state}, params) {
    api.checkAccount(params).then((res) => {
      commit('CHECK_ACCOUNT', {data: res})
    })
  },
  getIpOrgGrantRole ({commit, state}, params) {
    api.getIpOrgGrantRole(params).then((res) => {
      commit('ORG_GRANT_ROLE', {data: res.data})
    })
  }
}

// mutations
const mutations = {
  LOADING (state, data) {
    state.loading = data
  },
  ORG_GRANT_ROLE (state, {data}) {
    if (data && data.length > 0) {
      state.roleInfo = data[0]
    }
  }
}

const store = new Vuex.Store({
  state,
  actions,
  getters,
  mutations,
  modules: {
    tactical,
    sale,
    smartCourse,
    score,
    program,
    grade
  },
  strict: false,
  debug: debug
})

store.loader = loader
store.getHeaders = () => {
  let result = {}
  let token = Cookies.get('token')
  let userId = Cookies.get('userId')
  let timestamp = new Date().getTime()
  if (token) {
    result = {
      'X-SNS-UserId': userId,
      'X-SNS-Timestamp': timestamp,
      'X-SNS-Signature': sha1(userId + token + timestamp.toString()),
      'X-SNS-ClientType': 4
    }
  }
  return result
}

if (!Cookies.get('token') && location.href.indexOf('/login') === -1) {
  location.href = '/login'
}

export default store
